<template>
	<view class="page-wrapper">
		<!-- 状态栏占位 -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

		<!-- 顶部导航栏 -->
		<view class="navbar">
			<view class="nav-left" @click="goBack">
				<u-icon name="arrow-left" size="27" color="#fff"></u-icon>
			</view>
			<view class="nav-title">注册</view>
			<view class="nav-right" ></view>
			<!-- <view class="nav-right" @click="goLogin">登录</view> -->
		</view>

		<!-- 注册表单 -->
		<view class="register-container">
			<u-form :model="formData" :rules="rules" ref="formRef">

				<!-- 手机号输入 -->
				<u-form-item prop="phone">
					<u-input v-model="formData.phone" placeholder="请输入手机号" type="number" maxlength="11" border="bottom"
						style="height: 88rpx;">
						<template #prefix>
							<image src="@/static/img/login/icon-iphone@2x.png" mode="aspectFit"
								style="height: 39rpx;width: 27rpx; margin-right: 15rpx;margin-left: 11rpx;"></image>
						</template>
						<template #suffix>
							<u-text :text="countdown > 0 ? `${countdown}s后重新发送` : '发送验证码'" color="#ff5033" @click="sendCode" :disabled="countdown > 0"
								:customStyle="{ fontSize: '28rpx' }"></u-text>
						</template>
					</u-input>
				</u-form-item>

				<!-- 验证码输入 -->
				<u-form-item prop="code">
					<u-input v-model="formData.code" placeholder="请输入短信验证码" type="number" maxlength="6" border="bottom">
						<template #prefix>
							<u-icon name="email" size="28" color="#909399"></u-icon>
						</template>
					</u-input>
				</u-form-item>

				<!-- 邀请码输入 -->
				<u-form-item prop="inviteCode">
					<u-input v-model="formData.inviteCode" placeholder="请输入邀请码(可选)" type="text" class="input-field"
						border="bottom" style="height: 88rpx;">
						<template #prefix>
							<u-icon name="email" size="27" color="#909399"></u-icon>
						</template>
						<template #suffix>
							<u-icon name="scan" size="27" color="#909399" @click.stop="scanInviteCode"></u-icon>
						</template>
					</u-input>
				</u-form-item>


				<!-- 协议勾选 -->
				<view class="agreement-check">
					<label class="agreement-label">
						<text class="agreement-text">注册代表你已同意</text>
						<text class="agreement-link" @click="showUserAgreement">《优享优品平台注册协议》</text>
					</label>
				</view>

				<u-button type="primary" @click="register" color="#ff5033" text="下一步"
					:customStyle="{ borderRadius: '10rpx' }">
				</u-button>
			</u-form>
			<view class="login-link-container">
				<text class="login-prompt">已有账号？</text>
				<text class="login-link" @click="goLogin">立即登录</text>
			</view>

		</view>
	</view>
</template>

<script>
import api from '@/api/index.js'
import md5 from 'md5'

export default {
	data() {
		return {
			statusBarHeight: 0,
			formData: {
				phone: '',
				code: '',
				inviteCode: ''
			},
			rules: {
				phone: {
					type: 'string',
					required: true,
					message: '请输入手机号',
					trigger: ['blur', 'change']
				},
				code: {
					type: 'string',
					required: true,
					message: '请输入验证码',
					trigger: ['blur', 'change']
				}
			},
			agreeProtocol: true,
			codeText: '获取验证码',
			codeDisabled: false,
			countdown: 0,
			userIp: '', // 用户IP地址
			isPhoneChecked: false // 手机号是否已检查
		}
	},
	computed: {
		canRegister() {
			const phoneValid = this.formData.phone.length === 11;
			const codeValid = this.formData.code.length >= 4;
			const protocolValid = this.agreeProtocol;
			console.log('注册条件检查:', {
				phone: this.formData.phone,
				phoneValid,
				code: this.formData.code,
				codeValid,
				protocolValid,
				canRegister: phoneValid && codeValid && protocolValid
			});
			return phoneValid && codeValid && protocolValid;
		}
	},
	async onLoad(options) {
		// 获取状态栏高度
		const systemInfo = uni.getSystemInfoSync()
		this.statusBarHeight = systemInfo.statusBarHeight

		// 获取邀请码
		console.log('=== onLoad 邀请码初始化 ===')
		console.log('options:', JSON.stringify(options, null, 2))
		console.log('options.inviteCode:', options.inviteCode)

		if (options.inviteCode) {
			this.formData.inviteCode = options.inviteCode
			console.log('邀请码已设置:', this.formData.inviteCode)
		} else {
			console.log('未传入邀请码参数')
		}

		console.log('最终邀请码值:', this.formData.inviteCode)
		console.log('=== onLoad 邀请码初始化结束 ===')

		// 获取用户IP地址
		await this.getUserIp()
	},
	methods: {
		// 获取用户IP地址
		async getUserIp() {
			try {
				const result = await api.userApi.getIp()
				console.log('获取IP结果:', result)
				if (result.r === 0) {
					this.userIp = result.data
					console.log('用户IP地址:', this.userIp)
				} else {
					console.error('获取IP失败:', result.msg)
					// 如果获取IP失败，使用默认值
					this.userIp = '0.0.0.0'
				}
			} catch (error) {
				console.error('获取IP异常:', error)
				this.userIp = '0.0.0.0'
			}
		},

		// 返回上一页
		goBack() {
			const pages = getCurrentPages()
			if (pages && pages.length > 1) {
				uni.navigateBack()
			} else {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		},

		// 清空手机号
		clearPhone() {
			this.formData.phone = ''
			this.isPhoneChecked = false
		},

		// 检查手机号是否可用
		async checkMobile() {
			if (!this.formData.phone) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				})
				return false
			}

			if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				})
				return false
			}

			try {
				uni.showLoading({
					title: '检查中...'
				})

				const result = await api.userApi.checkMobile({
					mobile: this.formData.phone
				})

				uni.hideLoading()
				console.log('检查手机号结果:', result)

				if (result.r === 0) {
					if (result.data.is_used === 0) {
						// 手机号可用
						this.isPhoneChecked = true
						return true
					} else {
						// 手机号已注册
						uni.showToast({
							title: '该手机号已注册，请直接登录',
							icon: 'none'
						})
						return false
					}
				} else {
					uni.showToast({
						title: result.msg || '检查失败',
						icon: 'none'
					})
					return false
				}
			} catch (error) {
				uni.hideLoading()
				console.error('检查手机号失败:', error)
				uni.showToast({
					title: '网络异常，请重试',
					icon: 'none'
				})
				return false
			}
		},

		// 发送验证码
		async sendCode() {
			if (this.codeDisabled) return

			// 先检查手机号是否可用
			const canSend = await this.checkMobile()
			if (!canSend) return

			try {
				uni.showLoading({
					title: '发送中...'
				})

				const result = await api.userApi.sendCode({
					mobile: this.formData.phone,
					salt: "1234"
				})

				uni.hideLoading()
				console.log('发送验证码结果:', result)

				if (result.r === 0) {
					uni.showToast({
						title: result.msg || '验证码已发送',
						icon: 'success'
					})

					// 开始倒计时
					this.startCountdown()
				} else {
					uni.showToast({
						title: result.msg || '发送失败',
						icon: 'none'
					})
				}
			} catch (error) {
				uni.hideLoading()
				console.error('发送验证码失败:', error)
				uni.showToast({
					title: '网络异常，请重试',
					icon: 'none'
				})
			}
		},

		// 开始倒计时
		startCountdown() {
			this.codeDisabled = true
			this.countdown = 60
			this.codeText = `${this.countdown}s`

			const timer = setInterval(() => {
				this.countdown--
				if (this.countdown <= 0) {
					clearInterval(timer)
					this.codeDisabled = false
					this.codeText = '获取验证码'
				} else {
					this.codeText = `${this.countdown}s`
				}
			}, 1000)
		},

		// 注册
		async register() {
			if (!this.canRegister) return

			// 如果手机号未检查过，先检查
			if (!this.isPhoneChecked) {
				const canRegister = await this.checkMobile()
				if (!canRegister) return
			}

			try {
				uni.showLoading({
					title: '注册中...'
				})

				// 构建注册参数，按照API要求的格式
				// pwd使用验证码进行MD5加密
				const registerData = {
					mobile: this.formData.phone,
					pwd: md5(this.formData.code), // 使用验证码进行MD5加密作为密码
					invite_code: this.formData.inviteCode || '',
					region: 0,
					login_ip: this.userIp,
					salt: '1234',
					type: 1,
					longitude: 0,
					latitude: 0,
					unionid: '',
					openid: '',
					nickname: '',
					headimgurl: '',
					sex: ''
				}

				console.log('注册参数:', registerData)

				const result = await api.userApi.register(registerData)

				uni.hideLoading()
				console.log('注册结果:', result)

				if (result.r === 0) {
					// 处理注册成功逻辑
					const userInfo = result.data

					// 保存完整的用户信息
					uni.setStorageSync('user_info', userInfo)

					// 保存重要的用户数据
					if (userInfo.token) {
						uni.setStorageSync('token', userInfo.token)
					}
					if (userInfo.user_id) {
						uni.setStorageSync('user_id', userInfo.user_id)
					}
					if (userInfo.phone) {
						uni.setStorageSync('user_phone', userInfo.phone)
					}
					if (userInfo.username) {
						uni.setStorageSync('username', userInfo.username)
					}
					if (userInfo.invite_code) {
						uni.setStorageSync('invite_code', userInfo.invite_code)
					}
					if (userInfo.share_url) {
						uni.setStorageSync('share_url', userInfo.share_url)
					}

					// 保存用户权限信息
					const userPermissions = {
						is_partner: userInfo.is_partner || 0,
						is_agent: userInfo.is_agent || 0,
						is_general_agent: userInfo.is_general_agent || 0,
						is_merchant: userInfo.is_merchant || 0,
						is_staff: userInfo.is_staff || 0
					}
					uni.setStorageSync('user_permissions', userPermissions)

					// 保存地区信息
					const userRegion = {
						province_id: userInfo.province_id || 0,
						city_id: userInfo.city_id || 0,
						district_id: userInfo.district_id || 0,
						region: userInfo.region || 0
					}
					uni.setStorageSync('user_region', userRegion)

					console.log('用户信息已保存:', {
						userInfo,
						permissions: userPermissions,
						region: userRegion
					})

					uni.showToast({
						title: '注册成功',
						icon: 'success'
					})

					// 跳转到首页
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/index/index'
						})
					}, 1500)
				} else {
					uni.showToast({
						title: result.msg || '注册失败',
						icon: 'none'
					})
				}
			} catch (error) {
				uni.hideLoading()
				console.error('注册失败:', error)
				uni.showToast({
					title: '网络异常，请重试',
					icon: 'none'
				})
			}
		},

		// 跳转登录
		goLogin() {
			console.log('点击了登录按钮')
			try {
				uni.navigateTo({
					url: '/pages/login/login',
				})
			} catch (error) {
				console.error('跳转登录异常:', error)
			}
		},

		// 协议勾选状态改变
		onProtocolChange(e) {
			this.agreeProtocol = e.detail.value.length > 0;
			console.log('协议勾选状态:', this.agreeProtocol);
		},

		// 显示注册协议
		showUserAgreement() {
			uni.navigateTo({
				url: '/pages/identity/agreement'
			})
		},


	}
}
</script>

<style lang="scss" scoped>
.page-wrapper {
	background-color: #f5f5f5;
	min-height: 100vh;
}

.status-bar {
	background-color: #ff5033;
}

.navbar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 88rpx;
	padding: 0 30rpx;
	background-color: #ff5033;
	color: white;
}

.nav-left {
	width: 80rpx;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: flex-start;
}

.nav-title {
	font-size: 36rpx;
	font-weight: 500;
	color: white;
}

.nav-right {
	font-size: 32rpx;
	color: white;
	width: 80rpx;
	text-align: right;
}

.register-container {
	padding: 100rpx 50rpx;
	background-color: white;
	margin: 100rpx 40rpx;
	border-radius: 20rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.form-item {
	margin-bottom: 40rpx;
}

.input-wrapper {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #eee;
	position: relative;
}

.input-icon {
	width: 40rpx;
	height: 40rpx;
	margin-right: 20rpx;
}

.gift-icon {
	font-size: 32rpx;
	margin-right: 20rpx;
	width: 40rpx;
	text-align: center;
}

.input-field {
	flex: 1;
	font-size: 32rpx;
	color: #333;
	outline: none;
	background: transparent;
}

.input-field::placeholder {
	color: #999;
}

.clear-btn {
	padding: 10rpx;
	margin-left: 10rpx;
}

.clear-icon {
	font-size: 36rpx;
	color: #999;
	line-height: 1;
}

.code-btn {
	padding: 16rpx 24rpx;
	background: #ff5033;
	border-radius: 8rpx;
	margin-left: 20rpx;
	transition: all 0.3s ease;
}

.code-btn.disabled {
	background: #cccccc;
	pointer-events: none;
}

.code-text {
	font-size: 24rpx;
	color: #ffffff;
	font-weight: 500;
}

.register-btn {
	width: 100%;
	height: 88rpx;
	border-radius: 10rpx;
	border: none;
	margin-top: 40rpx;
	transition: all 0.3s ease;
}


.btn-text {
	font-size: 32rpx;
	color: #ffffff;
	font-weight: 500;
}

.agreement-check {
	margin: 40rpx 0;
	display: flex;
	align-items: center;
	justify-content: flex-start;
}

.agreement-label {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	margin-left: 15rpx;

}

.agreement-text {
	font-size: 26rpx;
	color: #999;
	margin: 0 5rpx;
}

.agreement-link {
	font-size: 26rpx;
	color: #ff5033;
	text-decoration: none;
	margin: 0 2rpx;
	font-weight: bold;
}

.agreement-link:active {
	color: #e6452e;
}

.login-link-container {
	margin-top: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 10rpx;
}

.login-prompt {
	font-size: 28rpx;
	color: #666666;
}

.login-link {
	font-size: 28rpx;
	color: #ff5033;
	font-weight: 600;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	transition: all 0.3s ease;
	position: relative;
}

.login-link:active {
	color: #ffffff;
	background-color: #ff5033;
	transform: scale(0.95);
}
</style>